package com.railway.news.util;

import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;

/**
 * 2011-12-07
 * 
 * @author z����
 *         ����һ��������ȡ��ҳԴ����������img��ǩ����Ϊ����ͼƬ���Ὣ��ͼƬ���ص����ز��ϴ���coo8���������·����
 *         ������ҳ����Ӧ��img��ǩ��src��Ϊ����·����
 */

public class ReloadImgUtils {
	private static final String s1 = "<img";
	private static final String s2 = "src=\"";
	private static final String s3 = "http://";
	private static final String s4 = "\"";
	private static final String s5 = ">";

	public static String reloadImgForUeditorSource(String source) {
		if (source == null || source.equals(""))
			return "nosource";
		int a = 0, b = 0, c = 0, d = 0, e = 0;
		List<String> oldSrcList = new ArrayList<String>();
		Map<String, String> newSrcMap = new HashMap<String, String>();
		for (int i = 0; i < source.length(); i++) {
			if (i == 0) {
				i = source.indexOf(s1);
				if (i == -1)
					break;
				if (i == 0)
					i = 3;
				b = source.indexOf(s2, i);
				if (b == -1)
					break;
				c = source.indexOf(s3, b);
				if (c == -1)
					break;
				d = source.indexOf(s4, c);
				if (d == -1)
					break;
				e = source.indexOf(s5, d);
				if (e == -1)
					break;
				if (b > i && b < c && c < d && d < e) {
					// ��ȡͼƬ��ַ�������ϴ������·��
					String src = source.substring(c, d);
					System.out.println(src);
					String path = getImgPathFromWebSite(src);
					System.out.println(path);
					// if(!StringUtil.isNullorBlank(src)&&!StringUtil.isNullorBlank(path)){
					// oldSrcList.add(src);
					// newSrcMap.put(src, path);
					// }
				}
				i = e;
				continue;
			}
			a = source.indexOf(s1, i);
			if (a == -1)
				break;
			b = source.indexOf(s2, a);
			if (b == -1)
				break;
			c = source.indexOf(s3, b);
			if (c == -1)
				break;
			d = source.indexOf(s4, c);
			if (d == -1)
				break;
			e = source.indexOf(s5, d);
			if (e == -1)
				break;
			if (b > i && b < c && c < d && d < e) {
				// ��ȡͼƬ��ַ�������ϴ������·��
				String src = source.substring(c, d);
				System.out.println(src);
				String path = getImgPathFromWebSite(src);
				System.out.println(path);
				// if(!StringUtil.isNullorBlank(src)&&!StringUtil.isNullorBlank(path)){
				// oldSrcList.add(src);
				// newSrcMap.put(src, path);
				// }
			}
			i = e;
		}

		if (oldSrcList.size() != 0 && newSrcMap.size() != 0) {
			for (String s : oldSrcList) {
				// if(StringUtil.isNullorBlank(s))
				// continue;
				source = source.replace(s, newSrcMap.get(s));
			}
		}

		System.out.println(source);
		return source;
	}

	// public static void main(String args[]){
	// String source = "<p>"+
	// " <img src=\"http://www.w8.com.cn/movie_pic/pic_2/12877.jpg\"
	// style=\"float:none;\" border=\"0\" height=\"667\" hspace=\"0\"
	// vspace=\"0\" width=\"450\" />"+
	// "</p><p>dfadfasdfas</p><p>hahdfhsadh</p><p>���Զ��Ѱ��������Ƿ���ط�����������°���</p><p>head������Ͱ�˹��</p><p>"+
	// "<img
	// src=\"http://a4.att.hudong.com/68/23/300000935727128981238080744_950.jpg\"
	// style=\"float:none;\" border=\"0\" height=\"763\" hspace=\"0\"
	// vspace=\"0\" width=\"550\" />"+
	// "</p><p>���������</p><p>���г�v<br /></p>";
	// reloadImgForUeditorSource(source);
	// }
	//	

	/**
	 * ���һ��Դ�����ַ���<img ��ǩ�ĸ���
	 * 
	 * @param source
	 * @return int
	 */

	public static int getImgNum(String source) {
		if (source == null || source.equals(""))
			return 0;
		int j = 0;
		for (int i = 0; i < source.length(); i++) {
			if (i == 0) {
				i = source.indexOf(s1);
				if (i == -1)
					break;
				if (i == 0)
					i = 3;
				j++;
				continue;
			}
			i = source.indexOf(s1, i);
			if (i == -1)
				break;
			j++;
		}
		return j;
	}

	/**
	 * �>���ַ��ȡͼƬ
	 * 
	 * @param WebSite
	 * @return Image
	 */
	public static String getImageByWebSite(String WebSite, String filename) {
		byte[] data = null;
		InputStream is = null;
		HttpURLConnection conn = null;
		try {
			URL url = new URL(WebSite);
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(6000);
			is = conn.getInputStream();
			if (conn.getResponseCode() == 200) {
				data = readInputStream(is);
			} else {
				data = null;
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			conn.disconnect();
		}
		if (data == null || data.length == 0)
			return null;
		String path = uploadImg(data, filename);
		return path;
	}

	/**
	 * �>���ַ��ȡ�ļ�������ַ�ַ����һ��"/"������ַ�
	 * ����http://www.baidu.com/index.html,���Ϊ��index.html
	 * 
	 * @param website
	 * @return String
	 */
	public static String getFileNameByWebSite(String website) {
		if (website == null || website.equals(""))
			return null;
		int a = website.lastIndexOf("/");
		if (a == -1)
			return null;
		String result = website.substring(a + 1);
		return result;
	}

	/**
	 * ��ͼƬ��ַ�л�ȡͼƬ��ʽ
	 * 
	 * @param website
	 * @return String
	 */
	public static String getFileTypeByWebSite(String website) {
		if (website == null || website.equals(""))
			return null;
		int a = website.lastIndexOf("/");
		if (a == -1)
			return null;
		String temp = website.substring(a + 1);
		if (temp == null || temp.equals(""))
			return null;
		int b = temp.indexOf(".");
		if (b == -1)
			return null;
		String result = temp.substring(b + 1);
		return result;
	}

	/**
	 * ������Ϣ�u�byte��������
	 * 
	 * @param is
	 * @return
	 */

	public static byte[] readInputStream(InputStream is) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		// �޶�ͼƬ��СΪ3M
		byte[] buffer = new byte[3145728];
		int length = -1;
		try {
			while ((length = is.read(buffer)) != -1) {
				baos.write(buffer, 0, length);
			}
			baos.flush();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		byte[] data = baos.toByteArray();
		try {
			is.close();
			baos.close();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return data;
	}

	/**
	 * �ϴ�ͼƬ�������ļ�ָ����λ��
	 * 
	 * @param file
	 * @param fileName
	 * @return String result
	 */
	public static String uploadImg(byte[] data, String fileName) {
		// String imgUploadAdress = ReloadableConfig.getProperty(
		// "ImgUploadAdress", "/app/publish/catalog/img/");
		// �����յ���byte��д��������
		String filePath = null;// imgUploadAdress + fileName;
		try {
			File file = new File(filePath);
			if (!file.getParentFile().isDirectory()) {
				file.getParentFile().mkdirs();
			}
			DataOutputStream out = new DataOutputStream(new FileOutputStream(
					file));
			for (int i = 0; i < data.length; i++) {
				out.write(data[i]);
			}
			out.flush();
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}

		// ����ļ��Ƿ���ͼƬ�����򷵻�·�������򷵻ؿ�
		String path = "http://p" + rd() + ".51mdq.com/img/publish/catalog/"
				+ fileName;
		if (checkFileIsImage(filePath)) {
			return path;
		}
		return null;
	}

	/**
	 * 1-4�������
	 * 
	 * @return
	 */
	public static int rd() {
		return new Random().nextInt(4) + 1;
	}

	/**
	 * ���һ���ļ����Ƿ������
	 */
	public static boolean checkFileNameIsContainChinese(String fileName) {
		if (fileName == null || fileName.equals(""))
			return false;
		if (fileName.getBytes().length != fileName.length())
			return true;
		return false;
	}

	/**
	 * ��������ļ�ָ��Ŀ¼���Ƿ���ͬ���ļ�
	 */
	public static boolean checkIsExitSameNameFile(String filename) {
		if (filename == null || filename.equals(""))
			return false;
		// String imgUploadAdress = ReloadableConfig.getProperty(
		// "ImgUploadAdress", "/app/publish/catalog/img/");
		// String filepath = imgUploadAdress + filename;
		// File file = new File(filepath);
		// if (file.exists())
		// return true;
		return false;
	}

	/**
	 * 2011-11-15 z���� ���һ�����������ļ���
	 * 
	 * @param filename
	 * @return
	 */
	public static String getNewFileName(String filename) {
		if (filename != null && !filename.equals("")) {
			String typ = filename.substring(filename.indexOf(".") + 1);
			filename = new Random().nextLong() + "." + typ;
			if (checkIsExitSameNameFile(filename)) {
				return getNewFileName(filename);
			}
			return filename;
		}
		return null;
	}

	/**
	 * ����ļ����Ƿ�Ϸ������򷵻�ԭ�ļ�����򷵻�һ���������ɵ��ļ���
	 */
	public static String getLegalFileNameFromName(String filename) {
		if (filename == null || filename.equals(""))
			return null;
		if (checkFileNameIsContainChinese(filename)) {
			filename = getNewFileName(filename);
			return filename;
		}
		if (checkIsExitSameNameFile(filename)) {
			filename = getNewFileName(filename);
			return filename;
		}
		return filename;
	}

	/**
	 * ����ļ����Ƿ�Ϸ������򷵻�ԭ�ļ�����򷵻�һ���������ɵ��ļ���
	 */
	public static String getLegalFileNameFromWebSite(String website) {
		if (website == null || website.equals(""))
			return null;
		String filename = getFileNameByWebSite(website);
		if (filename == null || filename.equals(""))
			return null;
		if (checkFileNameIsContainChinese(filename)) {
			filename = getNewFileName(filename);
			return filename;
		}
		if (checkIsExitSameNameFile(filename)) {
			filename = getNewFileName(filename);
			return filename;
		}
		return filename;
	}

	/**
	 * ���ͼƬ��ַ�Ƿ�ָ��coo8
	 * 
	 * @return
	 */
	public static boolean checkWebSiteIsCoo8Own(String website) {
		if (website == null || website.equals(""))
			return false;
		boolean flag = false;
		if (website.startsWith("p1.51mdq.com"))
			flag = true;
		else if (website.startsWith("http://p1.51mdq.com"))
			flag = true;
		else if (website.startsWith("p2.51mdq.com"))
			flag = true;
		else if (website.startsWith("http://p2.51mdq.com"))
			flag = true;
		else if (website.startsWith("p3.51mdq.com"))
			flag = true;
		else if (website.startsWith("http://p3.51mdq.com"))
			flag = true;
		else if (website.startsWith("p4.51mdq.com"))
			flag = true;
		else if (website.startsWith("http://p4.51mdq.com"))
			flag = true;
		return flag;
	}

	/**
	 * �>���ַ���ͼƬ �ϲ�����
	 */
	public static String getImgPathFromWebSite(String website) {
		if (website == null || website.equals(""))
			return null;
		if (checkWebSiteIsCoo8Own(website))
			return null;
		String filename = getLegalFileNameFromWebSite(website);
		String path = getImageByWebSite(website, filename);
		return path;
	}

	/**
	 * ��ָ֤��·�����ļ��Ƿ���ͼƬ
	 */
	public static boolean checkFileIsImage(String filepath) {
		if (filepath == null || filepath.equals(""))
			return false;
		File file = new File(filepath);
		if (file == null || !file.exists() || !file.canRead())
			return false;
		BufferedImage bi = null;
		try {
			// ����ļ��Ƿ���ͼƬ
			bi = javax.imageio.ImageIO.read(file);
			try {
				// �ж��ļ�ͼƬ�Ƿ�������ʾ,��ЩͼƬ���벻��ȷ
				bi.getType();
				return true;
			} catch (Exception e) {
				return false;
			}
		} catch (IOException e) {
			return false;
		}
	}

	public static void main(String argv[]) {
		try {
			File fi = new File("c:/image2.jpg"); // 大图文件
			File fo = new File("c:/imgTest.jpg"); // 将要转换出的小图文件
			int nw = 100;
			AffineTransform transform = new AffineTransform();
			BufferedImage bis = ImageIO.read(fi);
			int w = bis.getWidth();
			int h = bis.getHeight();
			double scale = (double) w / h;
			int nh = (nw * h) / w;
			double sx = (double) nw / w;
			double sy = (double) nh / h;
			transform.setToScale(sx, sy);
			System.out.println(w + " " + h);
			AffineTransformOp ato = new AffineTransformOp(transform, null);
			BufferedImage bid = new BufferedImage(nw, nh,
					BufferedImage.TYPE_3BYTE_BGR);
			ato.filter(bis, bid);
			ImageIO.write(bid, "jpeg", fo);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
